package channel;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import msg.SysMsg;


import database.Database;

import page.PageState;
import task.TaskCtrl;
import usr.Usr;

public class ChangeChannel extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession sess = req.getSession();
		Usr usr = (Usr)sess.getAttribute("usr");
		if(usr == null)
		{
			req.setAttribute("error_cause", PageState.LOGIN_NOT_EXIST);
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			return;
		}
		
		if ( usr.getCredit() != 0 ) {
			req.getRequestDispatcher("channels.jsp").forward(req, resp);
		} else {
			int id = Integer.parseInt(req.getParameter("id"));
			boolean enable = Boolean.parseBoolean(req.getParameter("enable"));
			
			try {
				Connection con = Database.getConnection();
				Statement stmt = con.createStatement();
				
				stmt.executeUpdate(String.format(
						"update channel " +
						"set enable = " + ((enable)? 1 : 0) + " " +
						"where id = %d",
						id));

				stmt.close();
				con.close();
				
				TaskCtrl.closeConcerningTasks(id);
				SysMsg.sendMsgToChannelUsr(usr.getId(), id);
				
				req.getRequestDispatcher("channels.jsp").forward(req, resp);
				
				
			} catch (SQLException e) {
				e.printStackTrace();
				req.getRequestDispatcher("u.html").forward(req, resp);
			}
			
		}
	}
}
